package com.yc.baseapi;

import java.lang.ref.WeakReference;
import java.util.Map;

//MyWeakHashMap为什么不能这么设计
public class MyWeakHashMap<K,V> {
	
	WeakReference<Entry<K,V>>[] table = new WeakReference[16];
	
	public V put(K key, V value) {
		int h = hash(key);
		WeakReference<Entry<K,V>>[] tab = table;
        int i = indexFor(h, tab.length);
        
        //循环执行下面这段逻辑
        if (tab[i].get() != null) {
        	Entry<K,V> it = tab[i].get();
        	if (key == it.getKey()) {
        		return it.getValue();
        	}
        } else {
        	tab[i] = new WeakReference<Entry<K,V>>(new Entry<K, V>());
        }
        
		return null;
	}
	
	public V get(Object key) {
        int h = hash(key);
        WeakReference<Entry<K,V>>[] tab = table;
        int index = indexFor(h, tab.length);
        Entry<K,V> e = tab[index].get();
        while (e != null) {
            if (key == e.getKey())
                return e.getValue();
        }
        return null;
		
	}
	
//	----------工具方法---------------
	final int hash(Object k) {
        int h = k.hashCode();
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }
    private static int indexFor(int h, int length) {
        return h & (length-1);
    }
	
//	---------------数据存储类---------------
	private static class Entry<K,V> implements Map.Entry<K,V> {

		@Override
		public K getKey() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public V getValue() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public V setValue(V value) {
			// TODO Auto-generated method stub
			return null;
		}
		
	}
	
}
